#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#define _DEBUG_

int print_result_set(char **azResult, int nrow, int ncolumn)
{

    int i;
    printf("nrow=%d ncolumn=%d\n", nrow, ncolumn);
    printf("the result is:\n");
    /* field name: azResult[0] ~ azResult[ncolumn-1] */
    for(i=0; i < (nrow+1)*ncolumn; i++)
    {
      printf("azResult[%d]=%s\n", i, azResult[i]);
    }

    return 0;
}

int db_travel_table(const char* db_file, const char* sql_file,
                    int (*cbfunc)(char **azResult, int nrow, int ncolumn) )
{
     sqlite3 *db=NULL;
     int len;
     int i=0;
     int nrow=0;
     int ncolumn = 0;
     char *zErrMsg =NULL;
     char **azResult=NULL; //二维数组存放结果
     /* 打开数据库 */
     len = sqlite3_open(db_file, &db);
     if( len )
     {
        /*  fprintf函数格式化输出错误信息到指定的stderr文件流中  */
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));//sqlite3_errmsg(db)用以获得数据库打开错误码的英文描述。
        sqlite3_close(db);
        return 1;
     }
     else printf("You have opened a sqlite3 database named user successfully!\n");

     FILE *fp = fopen(sql_file, "r");
     char sql[1024]; memset(sql, 0, 1024);
     int bytes = fread(sql, sizeof(sql), 1, fp);
     fclose(fp); fp=NULL;

        sqlite3_get_table( db , sql , &azResult , &nrow , &ncolumn , &zErrMsg );

    /* Call back function running... */
        cbfunc(azResult, nrow, ncolumn);

    #ifdef _DEBUG_
    printf("zErrMsg = %s \n", zErrMsg);
    sqlite3_free(zErrMsg);
    #endif

    sqlite3_close(db);

    return 0;
}

int main(int argc, char**argv)
{
    db_travel_table("../test3db", "../sql/left-join.sql", print_result_set );
    return 0;
 
}
